package com.s59.rabc.security;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;

public class CustomAuthorityDeserializer extends JsonDeserializer {
    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec();
        JsonNode jsonNode = mapper.readTree(jsonParser);
        LinkedList<SimpleGrantedAuthority> gregorianCalendars = new LinkedList<>();
        Iterator<JsonNode> element = jsonNode.elements();
        while (element.hasNext()){
            JsonNode next = element.next();
            JsonNode authrity = next.get("authority");
            gregorianCalendars.add(new SimpleGrantedAuthority(authrity.asText()));
        }
        return gregorianCalendars;
    }
}
